package com.lunker.moneyrecord;

import java.util.Calendar;
import java.util.Formatter;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class NewRecordActivity extends Activity implements OnClickListener {
	
	private static final int DATE_DIALOG_ID = 0;
	private static final String ZERO = "0";
	public static final int RESULT_YES = 2;
	public static final int RESULT_NO = 3;
	
	private TextView txt_amount;
	private TextView txt_date;
	private Spinner spr_catalog;
	private boolean dot = false;
	private StringBuilder amount = new StringBuilder(ZERO);
	private SQLiteDatabase mydb = null; 
	private int[] catalogIds = null; //IDs map to catalog names at the same position in array.
	private int year;
	private int month;
	private int day;
	private int catalogId;
	private Calendar today = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_record);
		
		mydb = new MyDatabaseOpenHelper(this).getWritableDatabase();		
		txt_amount = ((TextView) findViewById(R.id.txt_newRecordAmountValue));
		txt_date = ((TextView) findViewById(R.id.txt_newRecordDateValue));
		spr_catalog = ((Spinner) findViewById(R.id.spr_newRecordCatalog));
		//Set to default date to today, and default catalog to the first catalog in array.		
		today = Calendar.getInstance();
		year = today.get(Calendar.YEAR);
		month = today.get(Calendar.MONTH);
		day = today.get(Calendar.DAY_OF_MONTH);
		updateDisplayDate(year, month, day);
		catalogIds = getResources().getIntArray(R.array.catalog_id);
		catalogId = catalogIds[0];		
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, 
				R.array.catalog_name, R.layout.text_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		spr_catalog.setAdapter(adapter);
		spr_catalog.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {
				catalogId = catalogIds[pos];
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				//Do nothing.
			}
		});
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			Calendar c = Calendar.getInstance();
			return new DatePickerDialog(
					this,
					new DatePickerDialog.OnDateSetListener() {
						
						@Override
						public void onDateSet(DatePicker view, int year, int monthOfYear,
								int dayOfMonth) {
							
							NewRecordActivity.this.year = year;
							NewRecordActivity.this.month = monthOfYear;
							NewRecordActivity.this.day = dayOfMonth;
							updateDisplayDate(year, monthOfYear, dayOfMonth);
						}
					},
					c.get(Calendar.YEAR),
					c.get(Calendar.MONTH),
					c.get(Calendar.DAY_OF_MONTH));
		}
		
		return null;
	}

	@Override
	protected void onDestroy() {
		if (mydb != null) {
			mydb.close();
		}
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.txt_newRecordDateValue:
			showDialog(DATE_DIALOG_ID);
			break;
		case R.id.btn_clear:
			dot = false;
			amount = new StringBuilder(ZERO);
			txt_amount.setText(ZERO);
			break;
		case R.id.btn_dot:
			if (!dot) {
				dot = true;
				amount.append(".");
				txt_amount.setText(amount.toString());
			}
			break;
		case R.id.btn_0:
		case R.id.btn_1:
		case R.id.btn_2:
		case R.id.btn_3:
		case R.id.btn_4:
		case R.id.btn_5:
		case R.id.btn_6:
		case R.id.btn_7:
		case R.id.btn_8:
		case R.id.btn_9:
			if (amount.toString().equals(ZERO)) {
				//Don't start with 0.
				amount.replace(0, 1, ((Button) v).getText().toString());
			} else {
				amount.append(((Button) v).getText());
			}
			txt_amount.setText(amount.toString());		
			break;
		case R.id.btn_newRecordConfirm:
			//Add a new record.
			mydb.execSQL(new StringBuilder()
				.append("INSERT INTO money_record (year, month, day, amount, catalog) values (")
				.append(year)
				.append(", ")
				.append(month)
				.append(", ")
				.append(day)
				.append(", ")
				.append(txt_amount.getText().toString())
				.append(", ")
				.append(catalogId)
				.append(");")
				.toString()
			);
			updateWidget();
			Toast.makeText(this, getString(R.string.one_record_is_added), 
					Toast.LENGTH_SHORT).show();
			setResult(RESULT_YES);
			finish();
			break;
		case R.id.btn_newRecordCancel:
			setResult(RESULT_NO);
			finish();
			break;
		}
	}
	
	private void updateWidget () {
		new WidgetProvider().notifyChange(this);
	}
	
	private void updateDisplayDate (int year, int month, int day) {
		txt_date.setText(new Formatter().format("%d-%02d-%02d" , 
				year, (month + 1), day).toString());
	}
}
